<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../../themes/icon.css">
    <script type="text/javascript" src="../../jquery.min.js"></script>
    <script type="text/javascript" src="../../jquery.easyui.min.js"></script>
    <script type="text/javascript">
        $.extend($.fn.datagrid.methods, {
            editCell: function (jq, param) {
                return jq.each(function () {
                    var opts = $(this).datagrid('options');
                    var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor1 = col.editor;
                        if (fields[i] != param.field) {
                            col.editor = null;
                        }
                    }
                    $(this).datagrid('beginEdit', param.index);
                    var ed = $(this).datagrid('getEditor', param);
                    if (ed) {
                        if ($(ed.target).hasClass('textbox-f')) {
                            $(ed.target).textbox('textbox').focus();
                        } else {
                            $(ed.target).focus();
                        }
                    }
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor = col.editor1;
                    }
                });
            },
            enableCellEditing: function (jq) {
                return jq.each(function () {
                    var dg = $(this);
                    var opts = dg.datagrid('options');
                    opts.oldOnClickCell = opts.onClickCell;
                    opts.onClickCell = function (index, field) {
                        if (opts.editIndex != undefined) {
                            if (dg.datagrid('validateRow', opts.editIndex)) {
                                dg.datagrid('endEdit', opts.editIndex);
                                opts.editIndex = undefined;
                            } else {
                                return;
                            }
                        }
                        dg.datagrid('selectRow', index).datagrid('editCell', {
                            index: index,
                            field: field
                        });
                        opts.editIndex = index;
                        opts.oldOnClickCell.call(this, index, field);
                    }
                });
            }
        });

        $(function () {
            var arrays = [];
            var goodsCateServerDatas = [];
            var productsDomArray = [];

            $('#panel_detail').panel('close');
            $('#next_btn').linkbutton({
                onClick: function () {
                    if (selectedSpec.length == 0) {
                        $.messager.alert('警告', '请选择规格', 'warning');
                        return;
                    }
                    nextPanel();
                }
            });
            $('#create_btn').linkbutton({
                onClick: function () {
                    var submitForm = $('#submitForm');

                    var input_goods_title = $('#goods_title');
                    var goods_title = input_goods_title.textbox('getValue');
                    submitForm.append("<input type='hidden' name='goods.goodsName' value='" + goods_title + "'></input>");

                    var input_goods_cate = $('#goodsCateTree');
                    var tree = input_goods_cate.combotree('tree');
                    var selectNode = tree.tree('getSelected');
                    var goods_cate = selectNode.id;
                    var goods_type = selectNode.attributes.type;
                    submitForm.append("<input type='hidden' name='goods.catId' value='" + goods_cate + "'></input>");
                    submitForm.append("<input type='hidden' name='goods.typeId' value='" + goods_type + "'></input>");

                    var input_goods_tags = $('#goodsTagSelect');
                    var select_goods_tags = input_goods_tags.combobox('getValues');
                    $.each(select_goods_tags, function (i, n) {
                        submitForm.append("<input type='hidden' name='goodsReleTags[" + i + "].tagId' value='" + n + "'></input>");
                    });

                    var input_goods_price = $('#price');
                    var goods_price = input_goods_price.textbox('getValue');
                    submitForm.append("<input type='hidden' name='goods.goodsPrice' value='" + goods_price + "'></input>");

//                    var input_goods_market_price = $('#market_price');
//                    var input_goods_weight = $('#goods_weight');

                    var input_goods_brand = $('#goodsBrandSelect');
                    var goods_brand = input_goods_brand.combobox('getValue');
                    submitForm.append("<input type='hidden' name='goods.brandId' value='" + goods_brand + "'></input>");

                    $.each(selectedSpec, function (i, n) {
                        submitForm.append("<input type='hidden' name='goodsOpenSpecs[" + i + "].specId' value='" + n.specId + "'></input>");
                        $.each(n.specDetails, function (j, nn) {
                            submitForm.append("<input type='hidden' name='goodsOpenSpecValues[" + j + "].specId' value='" + n.specId + "'></input>");
                            submitForm.append("<input type='hidden' name='goodsOpenSpecValues[" + j + "].specValueId' value='" + nn.specDetailId + "'></input>");
                            submitForm.append("<input type='hidden' name='goodsOpenSpecValues[" + j + "].specValueRemark' value='" + nn.specDetailName + "'></input>");
                        });
                    });

                    var expParamsGrid = $('#expParamsGrid');
                    var exp_params = expParamsGrid.propertygrid('getChanges');
                    $.each(exp_params, function (i, n) {
                        submitForm.append("<input type='hidden' name='goodsReleExpandParams[" + i + "].expandparamId' value='" + n.id + "'></input>");
                        submitForm.append("<input type='hidden' name='goodsReleExpandParams[" + i + "].expangparamValueId' value='" + n.value + "'></input>");
                        submitForm.append("<input type='hidden' name='goodsReleExpandParams[" + i + "].expandparamValueName' value='" + n.valueName + "'></input>");
                    });

                    var basicParamsGrid = $('#basicParamsGrid');
                    var basic_params = basicParamsGrid.propertygrid('getChanges');
                    $.each(basic_params, function (i, n) {
                        submitForm.append("<input type='hidden' name='goodsReleParams[" + i + "].paramId' value='" + n.id + "'></input>");
                        submitForm.append("<input type='hidden' name='goodsReleParams[" + i + "].paramValue' value='" + n.value + "'></input>");
                    });

                    var addStste = $(".pro_status:checked").val();
                    submitForm.append("<input type='hidden' name='goods.goodsAdded' value='" + addStste + "'></input>");

                    $.each(productsDomArray, function (i, dom) {
                        var input_product_no = $(dom).find(".product_no");
                        var product_no_val = input_product_no.textbox('getValue');
                        submitForm.append("<input type='hidden' name='productVos[" + i + "].goodsInfoItemNo' value='" + product_no_val + "'></input>");

                        var input_product_title = $(dom).find(".product_title");
                        var product_title_val = input_product_no.textbox('getValue');
                        submitForm.append("<input type='hidden' name='productVos[" + i + "].goodsInfoName' value='" + product_title_val + "'></input>");
                        submitForm.append("<input type='hidden' name='productVos[" + i + "].goodsInfoSubtitle' value='" + product_title_val + "'></input>");

                        var table_product = $(dom).find(".product_store_and_price");
                        var productStocks = table_product.datagrid('getChanges');
                        console.log(productStocks);
                        $.each(productStocks, function (j, nn) {
                            submitForm.append("<input type='hidden' name='productVos[" + i + "].productWares[" + j + "].wareId' value='" + nn.id + "'></input>");
                            submitForm.append("<input type='hidden' name='productVos[" + i + "].productWares[" + j + "].wareStock' value='" + nn.storeValue + "'></input>");
                            submitForm.append("<input type='hidden' name='productVos[" + i + "].productWares[" + j + "].warePrice' value='" + nn.priceValue + "'></input>");
                        });
                    });
                }
            });

            //加载商品标签选择列表
            $.getJSON("http://localhost:8080/loadGoodsTags.htm", function (data) {
                var goodsTagDatas = [];

                $.each(data.objectList, function (i, n) {
                    goodsTagDatas.push({
                        "value": n.tagId,
                        "text": n.tagImg,
                        "title": n.tagName
                    });
                });

                $('#goodsTagSelect').combobox({
                    valueField: 'value',
                    textField: 'title',
                    data: goodsTagDatas,
                    multiple: true,
                    formatter: function (row) {
//                    console.log(row);
//                    var opts = $(this).combobox('options');
//                    console.log(opts);
                        var html = '<img src="' + row.text + '" height="30px;">';
                        return html;
                    }
                });
            });


            /**
             * 加载类型关联的品牌列表
             * @param data
             */
            function loadTypeBrans(data) {
                var goodsBrands = [];
                $.each(data.goodsTypeVo.brands, function (i, n) {
                    goodsBrands.push({
                        id: n.brand.brandId,
                        text: n.brand.brandName
                    });
                });
                $("#goodsBrandSelect").combobox({
                    data: goodsBrands,
                    valueField: 'id',
                    textField: 'text',
                });
            }

            var selectedSpec = [];

            /**
             * 加载类型关联的规格列表
             * @param data
             */
            function loadTypeSpecs(data) {
                var goodsSpecDatas = [];
                $.each(data.goodsTypeVo.specVos, function (i, n) {
                    var spec = n.goodsSpec;
                    var specDetails = n.goodsSpec.specDetails;
                    $.each(specDetails, function (j, nn) {
                        goodsSpecDatas.push({
                            "specId": spec.specId,
                            "specName": spec.specName,
                            "value": nn.specDetailId,
                            "text": nn.specDetailName
                        });
                    });
                });
                $('#specSelect').combobox({
                    valueField: 'value',
                    textField: 'text',
                    groupField: 'specName',
                    data: goodsSpecDatas,
                    multiple: true,
                    onSelect: function (record) {
//                        console.log(record);
                        var spec = null;
                        $.each(selectedSpec, function (i, n) {
                            if (record.specId == n.specId) {
                                spec = n;
                            }
                        });
                        if (spec == null) {
                            spec = {
                                specId: record.specId,
                                specName: record.specName,
                                specDetails: [{
                                    specDetailId: record.value,
                                    specDetailName: record.text
                                }]
                            };
                            selectedSpec.push(spec);
                        } else {
                            spec.specDetails.push({
                                specDetailId: record.value,
                                specDetailName: record.text
                            });
                        }
//                        console.log(selectedSpec);
                    },
                    onUnselect: function (record) {
//                        console.log(record);
//                        console.log(selectedSpec);
                        var index_spec = -1;
                        var index_specDetail = -1;
                        $.each(selectedSpec, function (i, n) {
                            if (record.specId == n.specId) {
                                index_spec = i;
                                $.each(n.specDetails, function (j, nn) {
                                    if (record.specDetailId == nn.specDetailId) {
                                        index_specDetail = j;
                                    }
                                });
                            }
                        });

                        var spec = selectedSpec[index_spec];
                        spec.specDetails.splice(index_specDetail, 1);//删除数据的元素
                        if (spec.specDetails.length == 0) {
                            selectedSpec.splice(index_spec, 1);//删除数组的元素
                        }
//                        console.log(selectedSpec);
                    }
                });
            }

            /**
             * 加载类型关联的扩展参数列表
             * @param data
             */
            function loadTypeExpParams(data) {
                var exp_params = [];
                $.each(data.goodsTypeVo.expandParams, function (i, n) {
                    var obj = {
                        "id": n.expandparamId,
                        "name": n.expandparamName
                    };

                    var selectDatas = [];
                    $.each(n.valueList, function (j, nn) {
                        selectDatas.push({
                            id: nn.expandparamValueId,
                            text: nn.expandparamValueName
                        });
                    });

                    obj["editor"] = {
                        "type": "combobox",
                        "options": {
                            valueField: 'id',
                            textField: 'text',
                            data: selectDatas
                        }
                    };

                    exp_params.push(obj);
                });

                var expParamsGrid_columns = [[
                    {field: 'id', title: '属性编号', hidden: true, width: 80},
                    {field: 'name', title: '属性名', width: 80},
                    {
                        field: 'value', title: '属性值', width: 80, formatter: function (value, row, index) {
                        var data = row.editor.options.data;
                        var text = value;
                        $.each(data, function (i, n) {
                            if (value == n.id) {
                                text = n.text;
                            }
                        });
                        return text;
                    }
                    },
                    {field: 'valueName', title: '属性值文字', hidden: true, width: 80},
                ]];

                $('#expParamsGrid').propertygrid({
                    columns: expParamsGrid_columns,
                    data: exp_params,
                    onEndEdit: function (index, row, changes) {
                        var data = row.editor.options.data;
                        var text = '';
                        $.each(data, function (i, n) {
                            if (changes['value'] == n.id) {
                                text = n.text;
                            }
                        });
                        row['valueName'] = text;
                    }
                });
            }

            /**
             * 加载类型关联的基本参数
             * @param data
             */
            function loadTypeBasicParams(data) {
                var basic_params = [];
                $.each(data.goodsTypeVo.params, function (i, n) {
                    var obj = {
                        "id": n.paramId,
                        "name": n.paramName,
                        "editor": {"type": "text"}
                    };
                    basic_params.push(obj);
                });
                var basicParamsGrid_columns = [[
                    {field: 'name', title: '属性名', width: 80},
                    {field: 'id', title: '属性编号', hidden: true, width: 80},
                    {field: 'value', title: '属性值', width: 80},
                ]];
                $('#basicParamsGrid').propertygrid({
                    columns: basicParamsGrid_columns,
                    data: basic_params
                });
            }

            $.getJSON("http://localhost:8080/loadGoodsCateVos.htm", function (data) {
                $.each(data, function (i, n) {
                    getArray(n);
                });
//                console.log(arrays);
                $.each(getChildren(0), function (i, obj) {
                    var node = {
                        id: obj.id,
                        text: obj.name,
                        state: "closed",
                        attributes: {
                            pId: obj.pId,
                            type: obj.type,
                            rate: obj.rate,
                            level: 0
                        },
                        children: []
                    };
                    buildTree(node);
                    goodsCateServerDatas.push(node);
                });
//                console.log(goodsCateServerDatas);
                $("#goodsCateTree").combotree({//组件赋值
                    data: goodsCateServerDatas,
                    onlyLeafCheck: true,
                    onBeforeSelect: function (node) {
                        if (node.attributes.level < 2) {
                            $.messager.alert('警告', '请选择最后一级别分类', 'warning');
                            return false;
                        }
                        return true;
                    },
                    onSelect: function (node) {
                        //请求类型数据加载页面其他内容
                        $.getJSON("http://localhost:8080/loadGoodsTypeVo.htm", {typeId: node.attributes.type}, function (data) {
//                            console.log(data);
                            $('#goodsHiddenParams').show();
                            loadTypeBrans(data);
                            loadTypeSpecs(data);
                            loadTypeExpParams(data);
                            loadTypeBasicParams(data);
                        });
                    }
                });
            });

            function getArray(goodsCate) {
                if (goodsCate) {
                    arrays.push({
                        id: goodsCate.catId,
                        name: goodsCate.catName,
                        pId: goodsCate.catParentId,
                        type: goodsCate.typeId,
                        grade: goodsCate.catGrade,
                        rate: goodsCate.catRate
                    });
                }
                var childrens = goodsCate.cateVos;
                if (childrens && childrens.length > 0) {
                    $.each(childrens, function (i, n) {
                        getArray(n);
                    });
                }
            }

            function getChildren(pId) {
                var childrens = new Array();
                $.each(arrays, function (i, n) {
                    if (n.pId == pId) {
                        childrens.push(n);
                    }
                });
                return childrens;
            }

            function buildTree(node) {
                var childrenObjs = getChildren(node.id);
                if (childrenObjs && childrenObjs.length > 0) {
                    $.each(childrenObjs, function (i, n) {
                        var temp = {
                            id: n.id,
                            text: n.name,
                            state: "closed",
                            attributes: {
                                pId: n.pId,
                                type: n.type,
                                rate: n.rate,
                                level: node.attributes.level + 1
                            },
                            children: []
                        };
                        node.children.push(temp);
                        buildTree(temp);
                    });
                } else {//如果节点下面没有子节点集合了，就去掉空集合和状态字段
                    delete node.children;
                    delete node.state;
                }
            }

            function nextPanel() {
                //生成规格组合
                var specGroup = new Array();
                var goods_spec_array = new Array();
                $.each(selectedSpec, function (i, n) {
                    var specObj = {
                        "specId": n.specId,
                        "specName": n.specName,
                        "specDetails": []
                    };
                    $.each(n.specDetails, function (j, nn) {
                        specObj.specDetails.push({
                            "specId": n.specId,
                            "specDetailId": nn.specDetailId,
                            "specDetailName": nn.specDetailName
                        });
                    });
                    goods_spec_array.push(specObj);
                });
                $.ajax({
                    url: 'http://localhost:8080/allSpecGroup.htm',
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(goods_spec_array),
                    async: false,
                    success: function (data) {
                        specGroup = data.allGroups;
                    }
                });

                //生成货品表单
                $.each(specGroup, function (i, n) {
                    var title = "";
                    $.each(n, function (j, nn) {
                        if (j == 0) {
                            title += nn.specDetailName;
                        } else {
                            title += "," + nn.specDetailName;
                        }
                    });
                    createProductFormPanel(i, title);
                });
                var productTabs = $('#goodsProducts').tabs({
                    border: false
                });

                $('#panel_basic').panel('close');
                $('#panel_detail').panel('open');
            }

            function createProductFormPanel(index, title) {
                var product_tab = $("#product_demo").find(".products").clone().attr("title", title);
                $('#goodsProducts').append(product_tab);
                productsDomArray.push(product_tab);

                var product_title = $("#goods_title").textbox('getValue') + "(" + title + ")";
                var product_price = $('#price').textbox('getValue');

                var input_product_no = product_tab.find(".product_no");
                var input_product_title = product_tab.find(".product_title");
                var product_prop_grid = product_tab.find(".product_store_and_price");

                input_product_no.textbox({
                    prompt: '请输入货品编号'
                });
                input_product_title.textbox({
                    value: product_title
                });

                $.getJSON("http://localhost:8080/loadWareHouses.htm", function (data) {
                    var server_datas = [];
                    $.each(data.wareHouseList, function (i, n) {
                        var obj = {
                            "id": n.wareId,
                            "name": n.wareName,
                            "storeValue": 0,
                            "priceValue": product_price
                        };
                        server_datas.push(obj);
                    });
                    product_prop_grid.datagrid({
                        columns: [[
                            {field: 'id', title: '仓库编号', hidden: true, width: 80},
                            {field: 'name', title: '仓库', width: 80},
                            {field: 'storeValue', title: '库存', width: 80, editor: 'numberbox'},
                            {field: 'priceValue', title: '价格', width: 80, editor: 'numberbox'}
                        ]],
                        data: server_datas
                    });
                    product_prop_grid.datagrid('enableCellEditing');
                });
            }
        });
    </script>
</head>
<body>
<div class="easyui-panel" title="基本信息" id="panel_basic" style="width:1000px;min-height:200px;"
     data-options="footer:'#footer_basic'">
    <div style="margin-top: 10px;margin-left: 10px;">
        商品分类: <input class="easyui-combotree" id="goodsCateTree" panelHeight="auto" style="width: 200px;">
    </div>
    <div style="margin-top: 10px;margin-left: 10px;">
        商品标题: <input class="easyui-textbox" id="goods_title" style="width:300px">
    </div>
    <div style="margin-top: 10px;margin-left: 10px;">
        商品标签:
        <input id="goodsTagSelect" style="width:100px;"/>
    </div>
    <div style="margin-top: 10px;margin-left: 10px;">
        销售价格: <input class="easyui-textbox" id="price" style="width:100px">
    </div>
    <div style="margin-top: 10px;margin-left: 10px;">
        市场价格: <input class="easyui-textbox" id="market_price" style="width:100px">
    </div>
    <div style="margin-top: 10px;margin-left: 10px;">
        重&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;量: <input class="easyui-textbox" id="goods_weight" style="width:100px">
    </div>
    <div style="margin-top: 10px;margin-left: 10px;">
        是否上架:
        <label class="radio-inline">
            <input type="radio" class="pro_status add" value="1">上架
        </label>
        <label class="radio-inline">
            <input type="radio" class="pro_status add" value="0">下架
        </label>
    </div>

    <div id="goodsHiddenParams" style="display: none">
        <div style="margin-top: 10px;margin-left: 10px;">
            商品品牌:
            <select id="goodsBrandSelect" style="width:100px;"></select>
        </div>
        <div style="margin-top: 10px;margin-left: 10px;">
            商品规格:
            <input id="specSelect" style="width:200px;"/>
        </div>
        <div style="margin-top: 10px;margin-left: 10px;">
            扩展参数:
            <table id="expParamsGrid" style="width:300px;"></table>
        </div>
        <div style="margin-top: 10px;margin-left: 10px;">
            基本参数:
            <table id="basicParamsGrid" style="width:300px;"></table>
        </div>
    </div>
</div>
<div id="footer_basic" style="padding:5px;">
    <a href="#" class="easyui-linkbutton" id="next_btn">下一步</a>
</div>

<div class="easyui-panel" title="详细信息" id="panel_detail" style="width:1000px;min-height:200px;"
     data-options="footer:'#footer_detail'">
    <div id="goodsProducts" style="width:700px;height:auto">
        <!--货品选项卡-->
    </div>
</div>
<div id="footer_detail" style="padding:5px;">
    <a href="#" class="easyui-linkbutton">上一步</a>
    <a href="#" class="easyui-linkbutton" id="create_btn">发布商品</a>
</div>

<div id="product_demo" style="display: none">
    <div class="products" title="">
        <div style="margin-top: 10px;margin-left: 10px;">
            编号: <input class="product_no" style="width:200px">
        </div>
        <div style="margin-top: 10px;margin-left: 10px;">
            标题: <input class="product_title" style="width:200px">
        </div>
        <div style="margin-top: 10px;margin-left: 10px;">
            库存以及价格:
            <table class="product_store_and_price" style="width:300px;"></table>
        </div>
    </div>
</div>

<form id="submitForm" style="display: none" action="" method="post" target=""></form>
</body>
</html>